<template>
  <el-button-group v-if="importBtns.length > 0 || exportBtns.length > 0">
    <el-button
      v-for="item in importBtns"
      @click="handleImportClick(item.f_Id, item.f_BtnName)"
      :key="item.f_Id"
      size="mini"
      icon="el-icon-upload2"
    >
      {{ $t(item.f_BtnName) }}
    </el-button>
    <l-dialog
      v-if="importBtns.length > 0"
      :title="$t(importName)"
      :visible.sync="importVisible"
      :width="600"
      :height="400"
      :hasBtns="false"
      @close="handleCloseImport"
      @opened="handleOpenedImport"
    >
      <div class="l-rblock" style="padding: 8px; padding-top: 36px">
        <div class="l-down-scheme-btn">
          <el-button size="mini" @click="handleDownScheme">{{
            $t("下载模版")
          }}</el-button>
        </div>
        <el-upload
          multiple
          action
          ref="importUpload"
          :http-request="myChunkedUpload"
          class="l-excel-import-upload"
          :data="param"
          :show-file-list="false"
          :on-progress="handleProgress"
          :on-success="handleSuccess"
        >
          <el-button size="mini" type="primary">Press and upload</el-button>
        </el-upload>
        <div class="l-rblock" style="padding-top: 8px">
          <div
            class="import-file-item"
            v-for="(item, index) in fileList"
            :key="index"
          >
            <i class="el-icon-document"></i>
            {{ item.name }}
            <div class="import-file-item-btn" v-if="item.response">
              <span class="snum">{{ item.response.res.data.data.success }}</span
              >/<span class="fnum">{{ item.response.res.data.data.fail }}</span>
              <span
                @click="handleErrorClick(item.response.res.data.data.data)"
                class="fnum-btn"
                v-if="item.response.res.data.data.fail > 0"
                >查看错误</span
              >
            </div>
            <el-progress
              v-if="!item.response"
              :percentage="item.percentage"
            ></el-progress>
          </div>
        </div>
        <l-dialog
          :title="$t('错误信息')"
          :width="1000"
          :height="600"
          :visible.sync="errorVisible"
        >
          <l-table :columns="columns" :dataSource="tableData"> </l-table>
        </l-dialog>
      </div>
    </l-dialog>
    <l-dialog
      v-if="exportBtns.length > 0"
      :title="$t(exportName)"
      :visible.sync="exportVisible"
      :width="600"
      :height="400"
      @ok="handleExport"
    >
      <div class="l-rblock export-wraper" style="padding: 8px">
        <el-alert
          title="Tips"
          type="warning"
          description="请勾选需要导出的字段"
          show-icon
          :closable="false"
          style="margin-bottom: 16px"
        >
        </el-alert>
        <el-checkbox-group v-model="exportGroup" size="small">
          <el-checkbox
            style="margin-bottom: 8px"
            v-for="item in exportColumns"
            :key="item.prop"
            :label="item.prop"
            border
            >{{ $t(item.label) }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </l-dialog>
    <!--导出-->
    <el-button
      v-for="item in exportBtns"
      @click="handleExportClick(item)"
      :key="item.f_Id"
      size="mini"
      icon="el-icon-download"
    >
      {{ $t(item.f_BtnName) }}
    </el-button>
  </el-button-group>
</template>
<script>
import { mapGetters } from "vuex";
import chunkedUpload from "../../../../util/chunkedUpload";

const api = window.$api.excel.export;
export default {
  name: "l-excel-btns",
  props: {
    // moduleCode: {
    //   type: String,
    //   default: "",
    // },
    pageModuleCode:String
  },
  data() {
    return {
      // excel 导入
      importBtns: [],

      importId: "",
      importName: "",
      importVisible: false,

      folderId: "",
      fileList: [],

      errorVisible: false,
      tableData: [],

      // excel 导出
      exportIsPage: false,
      exportData: [],
      exportBtns: [],
      exportName: "",
      exportVisible: false,
      exportColumns: [],
      exportGroup: [],
      exportInfo: {},
      exportIsCustmerForm: false,
    };
  },
  computed: {
    ...mapGetters(["token"]),
    param() {
      return {
        folderId: this.folderId,
      };
    },
    columns() {
      const res = [];
      for (var key in this.tableData[0]) {
        if (key == "导入错误") {
          res.push({ label: key, prop: key, minWidth: 300 });
        } else {
          res.push({ label: key, prop: key, minWidth: 160 });
        }
      }
      return res;
    },
    moduleCode(){
      if(this.pageModuleCode){
        return this.pageModuleCode
      }
      else{
        return this.$parent.moduleCode
      }
    },
  },
  created() {
    this.folderId = this.$uuid();
    this.init();
  },
  methods: {
    async init() {
      const apiImport = window.$api.excel.import;
      const apiExport = window.$api.excel.export;

      let moduleCode = this.moduleCode; // 调整为功能编码
      if (this.$validatenull(this.moduleCode)) {
        const url = this.$router.$lrRouter.getValue(this.$route);
        let module = this.$store.getters.modules.find(
          (t) => t.f_UrlAddress == this.$route.fullPath
        );
        if (!module) {
          module = this.$store.getters.modules.find(
            (t) => t.f_UrlAddress == url
          );
        }
        moduleCode = module.f_EnCode;
      }

      if (!this.$validatenull(moduleCode)) {
        this.importBtns = this.filterAuth(
          await this.$awaitWraper(apiImport.getList(moduleCode))
        );
        this.exportBtns = this.filterAuth(
          await this.$awaitWraper(apiExport.getList(moduleCode))
        );
      }
    },

    filterAuth(data) {
      data = data || [];
      if (!this.lr_pageAuthInfo.isAuth) {
        return data;
      } else if (
        this.lr_pageAuthInfo.data &&
        this.lr_pageAuthInfo.data.buttons
      ) {
        return data.filter(
          (t) => this.lr_pageAuthInfo.data.buttons.indexOf(t.f_ModuleBtnId) > -1
        );
      }
    },

    handleImportClick(id, name) {
      this.importId = id;
      this.importName = name;
      this.importVisible = true;
    },
    handleCloseImport() {},
    handleOpenedImport() {},
    handleProgress($event, $file, fileList) {
      this.fileList = this.$deepClone(fileList);
    },
    handleSuccess($res, $file, fileList) {
      this.fileList = fileList;
    },
    myChunkedUpload(option) {
      chunkedUpload(option, (data) => {
        const api = window.$api.excel.import;
        return api.upload(this.importId, data);
      });
    },
    handleDownScheme() {
      this.$downFile(
        `${this.apiUrl}excel/import/scheme/${this.importId}?token=${this.token}`,
        this.$t("File 下载成功")
      );
    },
    handleErrorClick(data) {
      this.errorVisible = true;
      this.tableData = data;
    },

    handleExportClick(item) {
      this.exportName = item.f_Name;

      const mainTable = this.getTable(this.$parent, item.f_GridId);
      if (mainTable.isMultiSelect && item.f_IsCheck == 1) {
        const selectList = mainTable.getSelected();
        if (selectList.length == 0) {
          this.$message({
            type: "warning",
            message: "please select数据!",
          });
          return;
        } else {
          this.exportData = JSON.parse(JSON.stringify(selectList));
        }
      } else {
        this.exportData = JSON.parse(JSON.stringify(mainTable.dataSource));
      }

      this.exportIsPage = mainTable.isPage ? true : false;
      this.exportColumns = mainTable.columns;
      this.exportGroup = mainTable.columns.map((t) => t.prop);
      this.exportInfo = item;

      // 处理列的小数点问题
      if (this.exportData.length > 0) {
        for (let key in this.exportData[0]) {
          if (this.$validatenull(this.exportData[0][key])) {
            this.exportData[0][key] = "";
          } else if (typeof this.exportData[0][key] == "number") {
            this.exportData[0][key] = this.exportData[0][key] + "";
          }
        }
      }

      if (this.$route.path == "/mycustmerform/module") {
        this.exportIsCustmerForm = true;
      } else {
        this.exportIsCustmerForm = false;
      }

      this.exportVisible = true;

      //console.log(mainTable)
    },
    async handleExport() {
      const loading = this.$loading({
        lock: true,
        text: "File 导出中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      // 组织参数
      let params = {
        fileName: this.exportInfo.f_Name,
        columns: this.exportColumns.filter(
          (t) => this.exportGroup.indexOf(t.prop) > -1
        ),
        isPage: this.exportIsPage,
      };

      // 设置自定义表单的导出数据链接
      if (this.exportIsCustmerForm) {
        params.isPost = true;
        if (this.exportIsPage) {
          this.exportInfo.f_Url = `custmerform/data/page/${this.getModuleId(
            this.$parent
          )}/${this.getFormId(this.$parent)}`;
        } else {
          this.exportInfo.f_Url = `custmerform/datas/${this.getModuleId(
            this.$parent
          )}/${this.getFormId(this.$parent)}`;
        }
      }

      // 导出数据

      if (this.exportInfo.f_Url) {
        const requestList = this.$store.state.app.request.filter(
          (t) => t.url == this.exportInfo.f_Url
        );
        if (requestList.length <= 0) {
          this.$message({
            type: "warning",
            message: "请重新query数据,再导出！",
          });
          return;
        }
        const requestObj = requestList[requestList.length - 1];
        let url = requestObj.url;

        if (requestObj.params) {
          url = `${url}?`;
          let isFirst = true;
          for (const key in requestObj.params) {
            let item = requestObj.params[key];
            if (key == "rows" && this.exportIsPage) {
              item = 100000;
            }
            if (key == "page" && this.exportIsPage) {
              item = 1;
            }

            if (isFirst) {
              url += `${key}=${item}`;
              isFirst = false;
            } else {
              url += `&${key}=${item}`;
            }
          }
        }

        if (requestObj.data) {
          params.isPost = true;
          if (this.exportIsPage) {
            requestObj.data.paginationInputDto.page = 1;
            requestObj.data.paginationInputDto.rows = 100000;
          }

          params.reqData = JSON.stringify(requestObj.data);
        }

        params.dataUrl = `${this.apiUrl}${encodeURI(url)}`;
      } else {
        params.dataList = this.exportData || [];
      }

      const id = await this.$awaitWraper(api.down(params));
      if (id) {
        this.$downFile(
          `${this.apiUrl}excel/export/file/${this.exportInfo.f_Name}/${id}?token=${this.token}`
        );
        this.exportVisible = false;
      } else {
        this.$message({
          type: "error",
          message: "导出失败",
        });
      }

      loading.close();
    },
    getTable(parent, id) {
      if (parent.$refs[id]) {
        return parent.$refs[id];
      } else if (parent.$parent) {
        return this.getTable(parent.$parent, id);
      }
    },
    getFormId(parent) {
      if (parent.lr_isPage) {
        return parent.formSchemeId;
      } else if (parent.$parent) {
        return this.getFormId(parent.$parent);
      }
    },
    getModuleId(parent) {
      if (parent.lr_isPage) {
        return parent.moduleId;
      } else if (parent.$parent) {
        return this.getModuleId(parent.$parent);
      }
    },
  },
};
</script>
<style lang="scss">
.l-down-scheme-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 11;
}

.l-excel-import-upload {
  position: absolute;
  top: 8px;
  left: 8px;
  z-index: 11;
}

.import-file-item {
  position: relative;
  box-sizing: border-box;
  cursor: pointer;
  width: 100%;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: color 0.3s;
  white-space: nowrap;
  line-height: 24px;

  &:hover {
    color: #409eff;
    background-color: #f5f7fa;
  }
}

.import-file-item-btn {
  position: absolute;
  top: 0;
  right: 8px;

  .snum {
    color: #409eff;
  }

  .fnum {
    color: #f56c6c;
  }

  .fnum-btn {
    color: #f56c6c;
    margin-left: 8px;
  }
}

.export-wraper {
  overflow: hidden auto;

  .el-checkbox {
    margin-right: 16px !important;
    margin-left: 0 !important;
  }
}
</style>